package message;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class LoginServlet extends HttpServlet {
	public void wrong3(){
		String msg="该用户尚未注册，登录失败！";
		int type=JOptionPane.YES_NO_CANCEL_OPTION;
		String title="信息提示";
		JOptionPane.showMessageDialog(null, msg, title, type);
	}
	public void wrong4(){
		String msg="用户密码不正确，登录失败！";
		int type=JOptionPane.YES_NO_CANCEL_OPTION;
		String title="信息提示";
		JOptionPane.showMessageDialog(null, msg, title, type);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String account=new String(request.getParameter("account").getBytes("ISO-8859-1"),"UTF-8");
		String password=new String(request.getParameter("password").getBytes("ISO-8859-1"),"UTF-8");
		try{
			Connection con=null;
			Statement stmt=null;
			ResultSet rs=null;
			Class.forName("com.mysql.jdbc.Driver");/*url后面的？useUnicode=true&characterEncoding=gbk，用于处理向数据库中添加数据时出现乱码的问题*/
			String url="jdbc:mysql://localhost:3306/bedroomallocation?useUnicode=true&characterEncoding=gbk";
			con=DriverManager.getConnection(url,"root","root");
			stmt=con.createStatement();
			String sql="select * from student where id='"+account+"'";
			rs=stmt.executeQuery(sql);
			int N=0;
			int P=0;
			while(rs.next()){
				if(account.equals(rs.getString("id"))){
					N=1001;
					if(password.equals(rs.getString("password"))){
						P=1001;
						//实例化保存个人信息的JavaBean
						LoginBean bean=new LoginBean();
						bean.setAccount(account);		//保存用户名
						bean.setPassword(password);		//保存密码
						bean.setMessage(rs.getString("message"));
						bean.setName(rs.getString("name"));
						bean.setClassName(rs.getString("className"));
						//获取session对象
						HttpSession session=request.getSession();
						ArrayList login=new ArrayList();		//实例化列表对象
						login.add(bean);
						/*把列表报讯到session对象中，以便在别的页面中获取个人信息*/
						session.setAttribute("login", login);
						response.sendRedirect("http://localhost:8888/BedroomAllocation/index.jsp");
					}else{}
				}else{N++;}
			}
			if(N<1001){
				wrong3();
				response.sendRedirect("http://localhost:8888/BedroomAllocation/login.jsp");
			}else if(P<1001){
				wrong4();
				response.sendRedirect("http://localhost:8888/BedroomAllocation/login.jsp");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doGet(request,response);
	}
	
	public void init() throws ServletException {
		// Put your code here
	}
	
}
